package main

import (
	"encoding/binary"
	"flag"
	"fmt"
	"log"
	"net"
	"os"
	"time"

	"gopkg.in/yaml.v2"
)

type Config struct {
	UDPPort           int    `yaml:"udp_port"`
	CommPhaseNo       int    `yaml:"comm_phase_no"`
	SequenceNo        int    `yaml:"sequence_no"`
	SendCount         int    `yaml:"send_count"`
	DelayMilliSeconds int    `yaml:"delay_seconds"`
	BroadcastAddress  string `yaml:"broadcast_address"`
}

var originBuffer = []byte{0x04, 0x00, 0x00, 0x46, 0x50, 0x4C, 0x00, 0x23, 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0xF0, 0x01, 0x00, 0x00, 0x40, 0x89, 0x00, 0x08, 0x0F, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0xc9, 0x02, 0x01, 0x00, 0x1F, 0x32, 0x30, 0x32, 0x35, 0x30, 0x33, 0x32, 0x35, 0x00, 0x30, 0x39, 0x3A, 0x32, 0x38, 0x3A, 0x31, 0x31, 0x00, 0x00, 0x00, 0x02, 0xF4, 0x32, 0x30, 0x32, 0x35, 0x30, 0x38, 0x31, 0x32, 0x00}

func main() {
	// 命令行参数
	udpPort := flag.Int("port", -1, "UDP port to send data to")
	commPhaseNo := flag.Int("comm", -1, "Communication phase number")
	sequenceNo := flag.Int("seq", -1, "Starting sequence number")
	sendCount := flag.Int("count", -1, "Number of times to send data")
	delayMilliseconds := flag.Int("delay", -1, "Delay between sends in milliseconds")
	broadcastAddress := flag.String("broadcast", "", "Broadcast address (e.g., 255.255.255.255)")
	configFile := flag.String("config", "config.yaml", "Path to config file (default: config.yaml)")
	flag.Parse()

	// 从配置文件加载（如果提供了）
	var config Config
	if *configFile != "" {
		data, err := os.ReadFile(*configFile)
		if err != nil {
			log.Fatalf("Failed to read config file: %v", err)
		}
		err = yaml.Unmarshal(data, &config)
		if err != nil {
			log.Fatalf("Failed to parse config file: %v", err)
		}
	}

	// 优先使用命令行参数，否则使用配置文件的值
	if *udpPort == -1 {
		*udpPort = config.UDPPort
	}
	if *commPhaseNo == -1 {
		*commPhaseNo = config.CommPhaseNo
	}
	if *sequenceNo == -1 {
		*sequenceNo = config.SequenceNo
	}
	if *sendCount == -1 {
		*sendCount = config.SendCount
	}
	if *delayMilliseconds == -1 {
		*delayMilliseconds = config.DelayMilliSeconds
	}

	// 验证参数
	if *udpPort == 0 || *commPhaseNo == 0 || *sendCount <= 0 {
		log.Fatal("Missing required parameters: udp_port, comm_phase_no, and send_count must be provided")
	}
	// 确定广播地址
	if *broadcastAddress == "" {
		*broadcastAddress = config.BroadcastAddress
	}

	conn, err := net.Dial("udp", fmt.Sprintf("%s:%d", *broadcastAddress, *udpPort))
	if err != nil {
		log.Fatalf("Failed to dial UDP: %v", err)
	}
	defer conn.Close()

	// 发送数据
	for i := 0; i < *sendCount; i++ {
		// 替换 CommPhaseNo（第 16 字节开始的 int32）
		binary.BigEndian.PutUint32(originBuffer[16:20], uint32(*commPhaseNo))

		// 替换 SequenceNo（第 20 字节开始的 int32）
		binary.BigEndian.PutUint32(originBuffer[20:24], uint32(*sequenceNo))

		// 发送数据
		_, err = conn.Write(originBuffer)
		if err != nil {
			log.Printf("Failed to send data: %v", err)
		} else {
			log.Printf("Sent: CommPhaseNo=%d, SequenceNo=%d", *commPhaseNo, *sequenceNo)
		}
		*sequenceNo++
		time.Sleep(time.Duration(*delayMilliseconds) * time.Millisecond)
	}
}
